package com.chat;

import java.io.IOException;
import java.net.*;

public class MsgReceiver implements Runnable {
    public void run() {
        DatagramSocket datagramSocket = null;
        byte[] buffer = new byte[1024];  // 定义容器存储空间。多大？
        InetAddress ip = null;
        try {
            ip = InetAddress.getByName("192.168.254.101");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        while(true){
            try {
                datagramSocket = new DatagramSocket(7001,ip);
                DatagramPacket msgBag = new DatagramPacket(buffer, buffer.length);
                datagramSocket.receive(msgBag);   // 往容器里加东西。
                String msg = new String(buffer, 0, msgBag.getLength());
                System.out.println("服务端说：" + msg);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(datagramSocket != null){
                    datagramSocket.close();
                }
            }
        }
    }
}
